﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;


using GrimorioApplication.Model;
using GrimorioApplication.Localization;
using System.Collections.ObjectModel;


namespace GrimorioApplication.Views
{
    public partial class AddQIng : PhoneApplicationPage
    {
        public AddQIng()
        {
            InitializeComponent();
            ApplicationBarInitializer();
            box_ingredient.ItemsSource = App.ViewModel.AllIngredients;
            box_ingredient.ItemFilter = SearchIngredient;
        }

        bool SearchIngredient(string search, object value)
        {
            if (value != null)
            {
                Ingredients datasourceValue = value as Ingredients;
                string name = datasourceValue.IngredientName;
                if (name.ToLower().StartsWith(search.ToLower()))
                    return true;
            }
            //... If no match, return false.
            return false;
        }

        private void ApplicationBarInitializer()
        {
            ApplicationBar = new ApplicationBar();
            ApplicationBar.Mode = ApplicationBarMode.Default;
            ApplicationBar.Opacity = 1.0;
            ApplicationBar.IsVisible = true;
            ApplicationBar.IsMenuEnabled = false;

            // save button
            ApplicationBarIconButton btn_save = new ApplicationBarIconButton();
            btn_save.IconUri = new Uri("/Img/appbar_save.png", UriKind.Relative);
            btn_save.Text = GrimorioLang.save;
            ApplicationBar.Buttons.Add(btn_save);
            btn_save.Click += new EventHandler(btn_save_Click);

            // undo button
            ApplicationBarIconButton btn_undo = new ApplicationBarIconButton();
            btn_undo.IconUri = new Uri("/Img/appbar_cancel.png", UriKind.Relative);
            btn_undo.Text = GrimorioLang.undo;
            ApplicationBar.Buttons.Add(btn_undo);
            btn_undo.Click += new EventHandler(btn_undo_Click);
        }


        private void btn_undo_Click(object sender, EventArgs e)
        {
            NavigationService.GoBack();
        }

        // Clicco su salva, creo un idMax contenente il numero di ingredienti nella obsCollection AllIngredients
        // Creo una lista di interi contenente tutti gli id degli ingredienti
        // Bool samename per sapere se ho trovato l'ingrediente
        // DataRecipe temporaryRecipe per salvarmi temporaneamente un oggetto che abbia i valori della ricetta temporanea creata in partenza(appena entrato nella view)
        // Scansiono la lista caricata con gli id, controllando che non ci sia il nome dell'ingrediente inserito pocanzi nella tabella degli ingredienti
        // 
        //
        private void btn_save_Click(object sender, EventArgs e)
        {
            int idMax = App.ViewModel.AllIngredients.Count;
            List<int> idList = App.ViewModel.getIngredientIdList();
            bool samename = false;
            int i = 0;
            DataRecipe temporaryRecipe = App.ViewModel.getRecipeWithSelectedId(App.ViewModel.getIdRecipeWithDefaultName());
            List<GrimorioApplication.ViewModel.IngredientsAndQuantity> listToCheck = App.ViewModel.getIngredientsAndQuantityOfRecipeSelected(App.ViewModel.getIdRecipeWithDefaultName());

            foreach (GrimorioApplication.ViewModel.IngredientsAndQuantity item in listToCheck)
            {
                if (item.ingredientName == box_ingredient.Text)
                {
                    MessageBox.Show("Ingredient Yet in List");
                    return;
                }
            }
            
            if (box_ingredient.Text == "")
            {
                MessageBox.Show(GrimorioLang.messagebox_nameRequiredIng,GrimorioLang.messagebox_warning,MessageBoxButton.OK);
                return;
            }

            while (i < idMax)
            {
                Ingredients temp = App.ViewModel.getIngredientWithID(idList[i]);

                if (box_ingredient.Text == temp.IngredientName)
                {
                    samename = true;
                    // Inserisco solo la quantità nella tabella di mezzo
                    RecipeIngredients recipeIngredientToAdd = new RecipeIngredients()
                    {
                        _ingredientID = temp.IngredientsID,
                        Quantity = quantityOfIngredient.Text,
                        _recipeID = temporaryRecipe.RecipeId,
                    };
                    App.ViewModel.AddRecipeToIng(recipeIngredientToAdd);
                    break;
                }
                i++;
            }
            if (!samename)
            {
                // Devo creare un nuovo oggetto ingrediente
                Ingredients newIngredient = new Ingredients()
                {
                    IngredientName = box_ingredient.Text,
                };
                App.ViewModel.AddIngredient(newIngredient);

                RecipeIngredients recipeIngredientToAdd = new RecipeIngredients()
                   {
                       _ingredientID = newIngredient.IngredientsID,
                       Quantity = quantityOfIngredient.Text,
                       _recipeID = temporaryRecipe.RecipeId
                   };
                App.ViewModel.AddRecipeToIng(recipeIngredientToAdd);
            }

            // A questo punto ho popolato il db con la lista di ingredienti selezionata e le relative quantità, tutte associate
            // alla ricetta Grimorio_TeMpOrArY_Recipe
            NavigationService.GoBack();
        }

        private void quantityOfIngredient_GotFocus_1(object sender, RoutedEventArgs e)
        {
            TextBox editBox = (TextBox)sender;
            editBox.Text = "";
        }

        private void quantityOfIngredient_LostFocus_1(object sender, RoutedEventArgs e)
        {
            if (quantityOfIngredient.Text == "")
                quantityOfIngredient.Text = "0";
        }
    }

    // Classe accessoria per la gestione di un unico elemento contenente i dettagli da inserire
    public class IngredientAndQuantity
    {
        public string IngredientName { get; set; }

        public string IngredientQuantity { get; set; }
    }
}